package com.demonzym.framework.net.json;

import org.json.JSONArray;
import org.json.JSONException;

public class MyJSONArray{
	JSONArray mJsonArry;
	
	public MyJSONArray(JSONArray jsonArr){
		mJsonArry = jsonArr;
	}

	public MyJSONArray() {
		mJsonArry = new JSONArray();
	}

	public MyJSONArray(String json) throws MyJSONException {
		try {
			mJsonArry = new JSONArray(json);
		} catch (JSONException e) {
			throw new MyJSONException(e.getMessage());
		}
	}

	public void put(int index, Object value) throws MyJSONException {
		if(mJsonArry != null){
			try {
				mJsonArry.put(index, value);
			} catch (JSONException e) {
				throw new MyJSONException(e.getMessage());
			}
		}
		else{
			throw new MyJSONException("not new mJsonArry");
		}
	}

	public String optString(int index) {
		if(mJsonArry != null){
			String str = mJsonArry.optString(index);
			if(str != null && str.equalsIgnoreCase("null"))
				return "";
			else
				return str;
		}
		
		return null;
	}

	public int length() {
		if(mJsonArry != null)
			return mJsonArry.length();
		
		return 0;
	}

	public MyJSONObject optJSONObject(int index) {
		if(mJsonArry != null)
			return new MyJSONObject(mJsonArry.optJSONObject(index));
		
		return null;
	}

	public void put(Object jsonObject) {
		if(mJsonArry != null){
			if(jsonObject instanceof MyJSONObject)
				mJsonArry.put(((MyJSONObject)jsonObject).mJsonObj);
			else if(jsonObject instanceof MyJSONArray)
				mJsonArry.put(((MyJSONArray)jsonObject).mJsonArry);
			else
				mJsonArry.put(jsonObject);
		}
	}

	public long optLong(int index) {
		if(mJsonArry != null)
			return mJsonArry.optLong(index);
		
		return 0;
	}
	
	@Override
	public String toString() {
		if(mJsonArry != null)
			return mJsonArry.toString();
		
		return super.toString();
	}
}
